<?php

class AdsController extends AppController {
  public $helpers = array('Html', 'TWSForm', 'Paginator');
  public $components = array('Session', 'Util', 'Upload');
  public $name = 'Ads';
  public $paginate;


  function __construct($request=null, $response=null) {
    parent::__construct($request, $response);
    $this->paginate = array(
        'limit' => Configure::read('App.pageResultLimit'),
        'order' => array(
            'Ad.start_date' => 'desc', 'Ad.end_date'=>'desc'
            ));
  }

  function index($adId = null) {
    $this->layout ='custom';
    if (empty($adId)){
      throw new NotFoundException();
    }
      $opts = array(
            'fields'=>array('Company.name','Company.description','Company.id as company_id','Company.image_path', 'Company.address', 'Company.phone' ,'Company.phone_additional',  'Company.fax', 'Company.email', 'Company.url', 'Company.facebook_url','Company.twitter_url','Company.pinterest_url','Company.service_id', 'Ad.id as ad_id','Ad.description as ad_description','Ad.start_date','Ad.end_date','Ad.single_photo', 'Ad.youtube_url'),
            'conditions'=>array('Ad.id'=>$adId,'Ad.start_date <= Now()','Ad.end_date >= Now()')
      );
      $ad = $this->Ad->find('all',$opts);
      if(!empty($ad)) {
        $adInfo = $ad[0];
        $this->set("title_for_layout","Isle Vow - ". $adInfo['Company']['name']);
        $this->set("meta_keywords","Isle Vow ". $adInfo['Company']['name']); //TODO
        $this->set("meta_description","Products being offered by ". $adInfo['Company']['name'] .' at Isle Vow'); //TODO
        
        //service info
        $this->loadModel('Service');
        $serviceInfo = $this->Service->find('first',array('conditions'=>array('Service.id'=>$adInfo['Company']['service_id']),'fields'=>array('Service.name','Service.id')));
        $youtubeId="";
        if(!empty($adInfo['Ad']) && !empty($adInfo['Ad']['youtube_url'])) {
          $youtubeId = $this->Util->getUrlQueryStringParameter($adInfo['Ad']['youtube_url'],"v");
        }
        //getting coupons
        $this->loadModel('Coupon');
        $couponInfo = $this->Coupon->find('all',array('conditions'=>array('Coupon.company_id'=>$adInfo['Company']['company_id']),'Coupon.start_date <=Now()','Coupon.end_date >=Now()'));
        $this->set(array('adInfo'=> $adInfo,'serviceInfo'=>$serviceInfo, 'youtubeId'=>$youtubeId, 'couponInfo'=>$couponInfo));

        //Checking for Photo Albums
        $this->loadModel('Album');
        $albums = $this->Album->find('all', array('conditions'=>array('Category.company_id'=>$adInfo['Company']['company_id'])));
        $this->set('albums',$albums);
        
      } else {
        throw new NotFoundException();
      }
  }

    //admin
  function admin_index() {
    $this->layout="admin";
    $this->set('ads', $this->paginate('Ad'));
  }

  function admin_main() {
    $this->layout="admin";
  }

  function admin_add() {
    $this->layout = "admin";
    $this->set('options', $this->Ad->Company->find('list', array('fields'=> array('Company.id','Company.name'), 'order'=>array('name'=>'asc')  )));
    $this->set('singleOptions', array('Y'=>'Yes','N'=>'No'));
    $test = $this->Ad->validate;
    if ($this->request->is('post')) {
      $this->_processAction($this->request, 'add');
    }
  }
    //admin
  function admin_edit($id = null) {
    $this->layout="admin";
    $this->set('options', $this->Ad->Company->find('list', array('fields'=> array('Company.id','Company.name'), 'order'=>array('name'=>'asc')  )));
    $this->set('singleOptions', array('Y'=>'Yes','N'=>'No'));
    $this->Ad->id = $id;
    if ($this->request->is('get')) {
      $this->request->data = $this->Ad->read();
      $this->request->data['Ad']['start_date'] = $this->Util->formatDate($this->request->data['Ad']['start_date'], true);
      $this->request->data['Ad']['end_date'] = $this->Util->formatDate($this->request->data['Ad']['end_date'], true);
    } else {
      //check for delete ad
      if (isset($this->request->data['deleteBtn'])) {
        $this->admin_delete($id);
      } else {
        $this->_processAction($this->request, 'edit', $id);
      }
    }
  }

    private function _processAction($dataIn, $action='add', $id=null) {
      $data = $this->_processRequestData($dataIn);
      $this->Ad->set($data);
      if ($this->Ad->validates()) {
        $data["Ad"]["start_date"] = $this->Util->formatDate($data["Ad"]["start_date"]);
        $data["Ad"]["end_date"] = $this->Util->formatDate($data["Ad"]["end_date"]);
        if (!empty($data["Ad"]["image_path"]) && !empty($data["Ad"]["image_path"]['name'])) {
          $imageUploaded = $this->Upload->uploadImage($data["Ad"]["image_path"], WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' .Configure::read('App.adsImageFolder'),null, null, null, true, Configure::read('App.adsImageWidth') );
          $data["Ad"]["image_path"] = Configure::read('App.adsImageFolder') . '/' . $imageUploaded;
          $data["Ad"]["image_thumb_path"] = Configure::read('App.adsImageFolder') . '/' . Configure::read('App.defaultThumbnailPrefix') . $imageUploaded;
        } else {
          if($action==='add') {
            $data["Ad"]["image_path"] = null;
            $data["Ad"]["image_thumb_path"] = null;
          } else {
            $data["Ad"]["image_path"] = isset($data["Ad"]["_image_path"]) ? $data["Ad"]["_image_path"] : null;
            $data["Ad"]["image_thumb_path"] = isset($data["Ad"]["_image_thumb_path"]) ? $data["Ad"]["_image_thumb_path"] : null;
          }
        }
        if ($this->Ad->save($data, false)) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index'));
        }
      } else {
        if($action!=='add') {
          //getting previous image
          $data['Ad']['image_path']=$data["Ad"]["_image_path"];
          $data['Ad']['image_thumb_path']=$data["Ad"]["_image_thumb_path"];
          $data['Ad']['id']=$id;
        }
        $this->request->data['Ad'] = $data['Ad'];
        $this->set('errors', $this->Ad->validationErrors);
      }
      if($action==='add') {
        $this->render('admin_add');
      } else {
        $this->render('admin_edit');
      }
  }

  //admin
  function admin_delete($id) {
    $this->layout="admin";
    $this->admin_deleteImage($id, false);
    if ($this->Ad->delete($id)) {
      $this->Session->setFlash('The record has been deleted.');
      $this->redirect(array('action' => 'index'));
    }
  }

  //admin
  function admin_deleteImage($id, $redirect=true) {
    $this->layout="admin";
    $image = $this->Ad->read('image_path', $id);
    $imagePath = $image['Ad']['image_path'];
    $imageThumbPath = $image['Ad']['image_thumb_path'];
    if (!empty($imagePath)) {
      $result = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imagePath);
      $resultThumb = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imageThumbPath);
      $this->Ad->save(array('Ad' => array('id' => $id, 'image_path' => '', 'image_thumb_path'=>'')), false, array('image_path','image_thumb_path'));
      if($redirect){
        $this->Session->setFlash('The image has been deleted.');
        $this->redirect(array('action' => 'edit', $id));
      }
    }
  }
}

?>
